博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
laravel 使用vue_使用Laravel和Vue.js构建留言簿
阅读量:2511 次
发布时间:2019-05-11

本文共 21441 字,大约阅读时间需要 71 分钟。

laravel 使用vue

( )

Welcome back again Scotch.io readers, in today’s lesson we will be building a Guestbook that looks exactly like this:

再次欢迎Scotch.io读者,在今天的课程中,我们将构建一个如下所示的留言簿:

GuestBook Preview

It looks cool, doesn’t it?

看起来很酷,不是吗?

You will not only build the Guestbook but you will learn few things about both Laravel and Vue.js:

您不仅将构建Guestbook,而且还将了解有关Laravel和Vue.js的一些知识:

  • New Laravel 5.5 Model Factory structure.

    Laravel 5.5模型工厂的新结构。
  • Testing API Endpoints with Postman and exporting them to be used by your teammates.

    使用Postman测试API端点并将其导出以供队友使用。
  • New Laravel 5.5 presets.

    新的Laravel 5.5预设
  • New Laravel 5.5 Transformers.

    新的Laravel 5.5变形金刚。
  • Creating and working with Vue.js components.

    创建和使用Vue.js组件。
  • Making Ajax calls with Laravel and Axios.

    使用Laravel和Axios进行Ajax调用。

( )

Installing Laravel is as simple as running a command in your terminal, cd into your www and execute:

安装Laravel非常简单,只需在终端中运行命令,将CD插入www并执行:

composer create-project --prefer-dist laravel/laravel guestbook

After that, you will need to create a configuration file and point your domain name to the public folder ( for me it is gonna be ) and make sure the storage and the bootstrap/cache directories are writable by your web server or Laravel will not run.

之后,您将需要创建一个配置文件,并将您的域名指向公用文件夹(对我来说,它将是 ),并确保您的存储bootstrap / cache目录是可写的Web服务器或Laravel将无法运行。

Note: Usually downloading Laravel via composer will set the application key for you, but if for whatever reason it didn’t work for you and you are getting either “No application encryption key has been specified.” or “The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths.” running this command will fixed it for you:

注意:通常通过composer下载Laravel会为您设置应用程序密钥,但是如果由于某种原因它对您不起作用,您将得到“未指定应用程序加密密钥”的信息。 或“唯一支持的密码是具有正确密钥长度的AES-128-CBC和AES-256-CBC。” 运行此命令将为您修复该问题:

php artisan key:generate

If you have done everything correctly then by browsing to should see this exact same page:

如果您已正确完成所有操作,则通过浏览至应会看到此页面完全相同:

( )

Laravel’s database configurations are stored inside the environment variables file, to set your database information copy the content of .env.example to a .env file:

Laravel的数据库配置存储在环境变量文件中,以设置数据库信息,将.env.example的内容复制到.env文件中:

cp .env.example .env

This is the part we are interested in:

这是我们感兴趣的部分:

DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=homesteadDB_USERNAME=homesteadDB_PASSWORD=secret

For me, I will be using SQLite, that means I’ll set the DB_CONNECTION to sqlite and remove the rest of the configs.

对我来说,我将使用SQLite ,这意味着我将把DB_CONNECTION设置为sqlite并删除其余的配置。

if you removed DB_DATABASE config key, Laravel will assume you are working with database located in database/database.sqlite. Make sure you create that by running:

如果删除了DB_DATABASE配置键,Laravel将假定您正在使用位于database / database.sqlite中的数据库。 确保通过运行以下命令进行创建:

touch database/database.sqlite

( )

For the Guestbook we will only need one model and migration, Let’s name it Signature.

对于Guestbook,我们只需要一个模型和迁移,我们将其命名为Signature

To create both these files we can run:

要创建这两个文件,我们可以运行:

php artisan make:model Signature -m

When passing the -m flag to the php artisan make:model command a migration will be generated for you. This little trick will save you a lot of time and keystrokes.

当将-m标志传递给php artisan make:model命令时,将为您生成一个迁移。 这个小技巧将为您节省很多时间和按键。

Here is what our migration will look like:

这是我们的迁移结果:

class CreateSignaturesTable extends Migration{
/** **_ Run the migrations. _** **_ @return void _**/ public function up() {
Schema::create('signatures', function (Blueprint $table) {
$table->increments('id'); $table->string('name'); $table->string('email'); $table->text('body'); $table->timestamp('flagged_at')->nullable(); $table->timestamps(); }); } /** _ Reverse the migrations. _ _ @return void _/ public function down() {
Schema::dropIfExists('signatures'); }}

The column names are self explanatory but if you are confused about what flagged_at does, it’s basically a timestamp column that will hold the date and time for when the signature got flagged/reported and it can be null for when the post hasn’t been flagged, pretty much the same way created_at, updated_at and deleted_at works.

列名是不言自明的,但是如果您对flagged_at的操作感到困惑,那么它基本上是一个时间戳列,它将保存标记/报告签名的日期和时间,对于未标记该帖子的日期和时间可以为null ,几乎与created_atupdated_atDeleted_at的工作方式相同。

Update your migration file, hit save and run the migration command:

更新您的迁移文件,点击保存并运行迁移命令:

php artisan migrate

Last thing on this chapter is adding our columns to the fillable array on the model itself to allow for mass-assignment.

本章的最后一件事是将我们的列添加到模型本身的可填充数组中,以允许进行质量分配。

/_*_ Field to be mass-assigned.__ @var array*/protected $fillable = ['name', 'email', 'body', 'flagged_at'];

If you don’t know what that means or what does it do, here’s a good explanation from the docs:

如果您不知道这意味着什么或做什么,那么这是文档中的一个很好的解释:

A mass-assignment vulnerability occurs when a user passes an unexpected HTTP parameter through a request, and that parameter changes a column in your database you did not expect. For example, a malicious user might send an is_admin parameter through an HTTP request, which is then passed into your model's create method, allowing the user to escalate themselves to an administrator.

当用户通过请求传递意外的HTTP参数,并且该参数更改了数据库中您没有期望的列时,就会发生批量分配漏洞。 例如,恶意用户可能通过HTTP请求发送is_admin参数,然后将其传递到模型的create方法中,从而允许用户将自己升级为管理员。

( )

Next step would be generating dummy data to work with and we will be using for that, Luckily for us Laravel 5.5 comes with a much cleaner way of storing these factories by putting each factory on its own file and giving us the ability to generate them using the command line.

下一步将生成要使用的伪数据,为此,我们将使用 。幸运的是,Laravel 5.5通过将每个工厂放在自己的文件中并使我们能够使用命令行生成它们。

So let’s go ahead and run:

因此,让我们继续运行:

php artisan make:factory SignatureFactory

And use to get fake data that matches our table structure:

并使用获取与我们的表结构匹配的伪造数据:

$factory->define(App\Signature::class, function (Faker $faker) {
return [ 'name' => $faker->name, 'email' => $faker->safeEmail, 'body' => $faker->sentence ];});

Our Signature model factory is ready, it’s time to generate some dummy data.

我们的签名模型工厂已经准备就绪,是时候生成一些虚拟数据了。

In your command line run: php artisan tinker Then:

在命令行中运行: php artisan tinker然后:

factory(App\Signature::class, 100)->create();

You can create as many records as you want by replacing 100 with a number of your choice.

您可以根据需要选择任意数量的100来创建任意数量的记录。

( )

定义路线 (Defining Our Routes)

We can define these three routes by registering a new resource and excluding the ones we won’t be using:

我们可以通过注册一个新资源并排除我们将不使用的资源来定义这三个路由:

  • GET: api/signatures this endpoint is responsible for fetching all signatures.

    GET: api / signatures此终结点负责获取所有签名。

  • GET: api/signature/:id this endpoint is responsible for fetching a single signature by its ID.

    GET: api / signature /:id此端点负责通过其ID提取单个签名。

  • POST: api/signatures this is the endpoint we will be hitting to save a new signature.

    POST: api / signatures这是我们将要保存新签名的端点。

routes/api.php:

路线/api.php:

Route::resource('signatures', 'Api\SignatureController')    ->only(['index', 'store', 'show']);
  • PUT: api/:id/report this endpoint is the one we will use to report a signature.

    PUT: api /:id / report此端点是我们将用来报告签名的端点。

routes/api.php

路线/api.php

Route::put('signatures/{signature}/report', 'Api\ReportSignature@update');

创建控制器 (Creating The Controllers)

As you can already see in the routes definition section, the controllers we will need are SignatureController and ReportSignature.

如您在路由定义部分中已经看到的那样,我们将需要的控制器是SignatureControllerReportSignature

  • Generating and writing SignatureController

    生成和编写SignatureController
php artisan make:controller Api/SignatureController

And this is what it will contain:

这将包含以下内容:

ignoreFlagged() ->paginate(20); return SignatureResource::collection($signatures); } /** _ Fetch and return the signature. _ _ @param Signature $signature _ @return SignatureResource _/ public function show(Signature $signature) {
return new SignatureResource($signature); } /** _ Validate and save a new signature to the database. _ _ @param Request $request _ @return SignatureResource _/ public function store(Request $request) {
$signature = $this->validate($request, [ 'name' => 'required|min:3|max:50', 'email' => 'required|email', 'body' => 'required|min:3' ]); $signature = Signature::create($signature); return new SignatureResource($signature); }}

As you can see in our index method, we are using a scope with the name of ignoreFlagged to only return the signatures that hasn’t been flagged. You can define it by adding these lines to your Signature Model:

如您在索引方法中所看到的,我们正在使用名称为ignoreFlagged的作用域仅返回未标记的签名。 您可以通过将以下行添加到签名模型来定义它:

/_* _ Ignore flagged signatures. _ _ @param $query _ @return mixed _/public function scopeIgnoreFlagged($query){
return $query->where('flagged_at', null);}
  • Generating and writing ReportSignature

    生成并编写ReportSignature
php artisan make:controller Api/ReportSignature

And this is what it will contain:

这将包含以下内容:

flag(); return $signature; }}

When we retrieve the signature using Laravel Model Binding feature we call a flag method on it which simply sets the flagged_at column value to the current datetime, same way Laravel Soft Delete works. You can add this functionality by defining this method in your Signature Model:

当我们使用Laravel模型绑定功能检索签名时,我们在其上调用一个flag方法,该方法只是将flagged_at列值设置为当前日期时间,与Laravel Soft Delete的工作方式相同。 您可以通过在签名模型中定义以下方法来添加此功能:

/_* _ Flag the given signature. _ _ @return bool */public function flag(){
return $this->update(['flagged_at' => \Carbon\Carbon::now()]);}

( )

Laravel 5.5 ships with a really cool feature, if you are familiar with creating APIs then you clearly know that you always need to transform your data and not actually exposing your database table structure to your clients because if you’ll break anything that is relying on your API if you changed your table structure and for security purposes too. Nothing good comes from exposing your database structure.

Laravel 5.5附带了一个非常酷的功能,如果您熟悉创建API的话,那么您清楚地知道,您始终需要转换数据,而实际上并不需要向客户公开数据库表结构,因为如果您破坏了所有依赖的内容您的API(如果您更改了表结构以及出于安全目的)。 公开数据库结构无济于事。

In our case we will only need a Signature transformer, to create it we can run this command:

在我们的例子中,我们只需要一个签名转换器,就可以运行以下命令来创建它:

php artisan make:resource SignatureResource

And this will be its content:

这将是其内容:

$this->id, 'name' => $this->name, 'avatar' => $this->avatar, 'body' => $this->body, 'date' => $this->created_at->diffForHumans() ]; }}

Because we are calling an avatar property we don’t have, we need to write an accessor for it. Having this in our Signature Model is also perfect because we don’t want to expose our guests email addresses.

因为我们正在调用一个没有的头像属性,所以我们需要为其编写一个访问器。 在我们的“ 签名模型”中使用它也很完美,因为我们不想公开来宾的电子邮件地址。

/_* _ Get the user Gravatar by their email address. _ _ @return string  */public function getAvatarAttribute(){
return sprintf('https://www.gravatar.com/avatar/%s?s=100', md5($this->email));}

( )

After creating our endpoints, controllers and transformers, it’s time to test it! Let’s make sure everything is working as we’d expect. You might be asking me “But, Rachid? Why are we using Postman? We can simply use our browser for this?” And yes! I agree with you; we can use our browser to test this API, but if you are not actually writing your tests ( which you should do BTW! ) then I recommend you to test it with Postman because at least you can save those tests and run them again instead of opening the browser every time you make a change.

创建了端点,控制器和变压器之后,就该进行测试了! 让我们确保一切正常。 您可能会问我“但是,拉希德? 我们为什么要使用邮递员? 我们可以简单地使用我们的浏览器吗?” 是的! 我同意你的看法; 我们可以使用我们的浏览器来测试该API,但是如果您实际上并未编写测试(您应该这样做BTW!),那么我建议您使用Postman对其进行测试,因为至少您可以保存这些测试并再次运行它们,而不是每次进行更改时都打开浏览器。

To install Postman, browse to their website and pick the one that will work for you based on your OS.

要安装邮递员,请浏览其网站 并根据您的操作系统选择适合您的工作 。

I created a collection named Scotch Guestbook and put all my tests in it, you can do the same by clicking the New button and selecting the Collection option

我创建了一个名为Scotch Guestbook的集合,并将所有测试放入其中,您可以通过单击“ 新建”按钮并选择“ 集合”选项来执行相同的操作

Give it a name, a description and hit Create:

给它起一个名字,一个描述,然后点击Create

After creating your test, click Save and give it a name, a description, select a collection and hit Save:

创建测试后,点击保存,并为其命名,描述,选择一个集合并点击保存

测试我们的API端点 (Testing Our API Endpoints)

  • List of all signatures:

    所有签名列表:

  • Finding a signature by its ID:

    通过其ID查找签名:

  • Creating a new signature:

    创建一个新的签名:

  • Reporting a signature:

    报告签名:

I will include this collection with the project code source in GitHub.

我将把这个集合与GitHub中的项目代码源一起包括在内。

( )

By now, we are pretty much done with backend, the only remaining thing is to link our back with the frontend.

到现在为止,我们已经完成了后端的工作,剩下的唯一事情就是将我们的后端与前端连接起来。

主页设置 (Homepage Setup)

GET: / This is our GuestBook entry point, it is responsible for rendering the home page.

GET: /这是我们的GuestBook入口点,它负责呈现主页。

routes/web.php:

路线/web.php:

Route::get('/', 'SignaturesController@index')->name('home');

Then we create our controller by running:

然后,我们通过运行以下内容创建控制器:

php artisan make:controller SignaturesController

And this will be its content:

这将是其内容:

After that, we need to create our signatures.index view. Inside /resources/views/ create a master.blade.php file which will hold the website layout and allow for the other pages to extend it:

之后,我们需要创建我们的signatures.index视图。 在/ resources / views /内创建一个master.blade.php文件,该文件将保存网站布局并允许其他页面扩展它:

    
Scotch.io GuestBook
@yield('content')

Then, we create a new view inside a signatures folder with the name of index.blade.php

然后,我们在签名文件夹内创建一个新索引 ,名称为index.blade.php。

@extends('master')@section('content')
@endsection

签名创建页面设置 (Signature Creation Page Setup)

  • GET: /sign This page is responsible for displaying the form for creating a new signature.

    GET: / sign此页面负责显示用于创建新签名的表单。
Route::get('sign', 'SignaturesController@create')->name('sign');

We have already created that controller, so let’s add this method to it:

我们已经创建了该控制器,因此让我们向其添加此方法:

/_* _ Display the GuestBook form page. _ _ @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */public function create(){
return view('signatures.sign');}

And the view will be named sign.blade.php and located at resources/views/signatures/

该视图将被命名为sign.blade.php ,位于资源/视图/签名/

@extends('master')@section('content')
@endsection

( )

Before 5.5, Laravel has shipped with Bootstrap and Vue.js scaffolding, but not everyone wants to use either of those technologies, so with Laravel 5.5 you can now replace those with the ones you like simply by running this to switch to React

在5.5之前的版本中,Laravel附带了Bootstrap和Vue.js脚手架,但是并不是每个人都想使用其中任何一种技术,因此,通过Laravel 5.5,您现在可以简单地通过运行此程序以切换到React来用您喜欢的技术替换它们。

php artisan preset react

Or this if you are only interested in Bootstrap but not in any of those JS Frameworks:

如果您仅对Bootstrap感兴趣,而对那些JS框架都不感兴趣,则可以这样做:

php artisan preset bootstrap

Or you can run this if you don’t want any scaffolding to be generated out of the box by Laravel:

或者,如果您不希望Laravel开箱即用地生成任何脚手架,则可以运行此命令:

php artisan preset none

In our case, we will keep Vue.js and Bootstrap preset, so go ahead and run to install our JavaScript dependencies:

在我们的例子中,我们将保留Vue.js和Bootstrap的预设,因此继续安装我们JavaScript依赖项:

npm install

Open /resources/assets//sass/app.scss and add this styling I already created for our project

打开/resources/assets//sass/app.scss并添加我已经为我们的项目创建的样式

$color_1: #f14444;$color_2: #444;$color_3: #fff;$border_color_1: #ccc;$border_color_2: #fff;$border_color_3: #f14444;nav.navbar-findcond {
background: #fff; border-color: $border_color_1; box-shadow: 0 0 2px 0 #ccc; a {
color: $color_1; } ul.navbar-nav {
a {
color: $color_1; border-style: solid; border-width: 0 0 2px 0; border-color: $border_color_2; &:hover {
background: #fff; border-color: $border_color_3; } &:visited {
background: #fff; } &:focus {
background: #fff; } &:active {
background: #fff; } } } ul.dropdown-menu {
>li {
>a {
color: $color_2; &:hover {
background: #f14444; color: $color_3; } } } }}button[type="submit"] {
border-radius: 2px; color: $color_3; background: #e74c3c; padding: 10px; font-size: 13px; text-transform: uppercase; margin: 0; font-weight: 400; text-align: center; border: none; cursor: pointer; width: 10%; transition: background .5s; &:hover {
background: #2f3c4e; }}

Then run this command to compile it:

然后运行以下命令进行编译:

npm run dev

( )

At this point, the only thing remaining before we launch our amazing app is to create the two components we referenced:

在这一点上,我们启动惊人的应用程序之前剩下的唯一事情就是创建我们引用的两个组件:

Go ahead and create those two files in /resources/assets/components/js/

继续在/ resources / assets / components / js /中创建这两个文件

  • Signatures.vue

    签名
  • SignatureForm.vue

    SignatureForm.vue

And register them ( right before we create the new Vue instance ) so that our app can know about them. Open /resources/assets/app.js

并注册它们(在创建新的Vue实例之前),以便我们的应用程序可以了解它们。 打开/resources/assets/app.js

Vue.component('signatures', require('./components/Signatures.vue'));Vue.component('signature-form', require('./components/SignatureForm.vue'));const app = new Vue({
el: '#app'});

( )

To display a paginated list of signatures, I will be using you can install it by running this command:

要显示签名的分页列表,我将使用您可以通过运行以下命令来安装它:

npm install vuejs-paginate --save

Register it in our /resources/assets/app.js file

在我们的/resources/assets/app.js文件中注册

Vue.component('paginate', require('vuejs-paginate'));

And this will be content of our Signatures component:

这将是我们签名组件的内容:

As you can see above, when the component gets created we call the fetch method which is making a GET request to the endpoint we defined in the data object, then we set our signatures array to the value returned from our API.

正如您在上面看到的那样,当创建组件时,我们调用fetch方法,该方法向在数据对象中定义的端点发出GET请求,然后将签名数组设置为从API返回的值。

In our HTML, we iterate through the signatures and display them. When a user clicks on the report link we fire the report method which takes the ID of the signature as a param and makes a PUT request to hide the reported signature and calls the removeSignature which is responsible of removing it from the array.

在我们HTML中,我们遍历签名并显示它们。 当用户单击报告链接时,我们将启动报告方法,该方法将签名的ID作为参数,并发出PUT请求以隐藏报告的签名,并调用removeSignature ,该签名负责将其从数组中删除。

( )

For the SignatureForm component, we created the form, bound our inputs to our data object. When the guest fills in the form and clicks the submit button we fire a POST request to save the new signature, if everything goes well we change our saved property to true and reset the form, if not we assign our errors property to whatever Laravel Validation returns and display them.

对于SignatureForm组件,我们创建了表单,将输入绑定到数据对象 。 当访客填写表单并单击提交按钮时,我们会发出POST请求以保存新签名,如果一切顺利,我们将保存的属性更改为true并重置表单,否则,我们将errors属性分配给任何Laravel验证返回并显示它们。

After creating these two components or making changes to them, don’t forget to run this command to compile them.

创建这两个组件或对其进行更改后,请不要忘记运行此命令来对其进行编译。

npm run dev

( )

I hope you learnt a thing or two from this post, if you are working along and faced an issue I can help with, please do comment below and let me know of it. If you want to have a chat, I am on Twitter, come and say Hi!

希望您能从这篇文章中学到一两件事,如果您正在努力解决遇到的问题,我可以为您提供帮助,请在下面进行评论,并让我知道。 如果您想聊天,我是Twitter上的 ,快来打个招呼!

Stay tuned for more Vue.js tutorials and see you soon!

请继续关注更多Vue.js教程,很快再见!

翻译自:

laravel 使用vue

转载地址:http://fhuwd.baihongyu.com/

你可能感兴趣的文章
Java 笔记07
查看>>
POJ 3041 Asteroids (二分匹配)
查看>>
响应式布局
查看>>
缺陷跟踪系统Mantis之安装篇(转载)
查看>>
UI1_UITableViewHomeWork
查看>>
简单解析依赖注入(控制反转)在Spring中的应用
查看>>
NoSQL 简介及什么是AICD
查看>>
hibernate+mysql的连接池配置
查看>>
条件运算符 (?:)
查看>>
javascript Array(数组)
查看>>
HDU1518 Square 【剪枝】
查看>>
桥接模式
查看>>
crm查询记录共享给了哪些人
查看>>
android windows 上JNI编程
查看>>
IOS的UITextField,UIButton,UIWebView它描述的一些属性和IOS提示图像资源
查看>>
现代信息环境中的云计算
查看>>
面向对象-多态
查看>>
I/ O流的输出流应用
查看>>
[PTA] 数据结构与算法题目集 6-11 先序输出叶结点
查看>>
Selection Sort
查看>>